package com.yuri.news.controller;

import java.util.ArrayList;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.yuri.news.domain.Pages;
import com.yuri.news.domain.Result;
import com.yuri.news.entity.Role;
import com.yuri.news.service.RoleService;
import com.yuri.news.tool.Tool;

/**
 * 角色控制器
 * @author Yuri
 *
 */
//允许跨域请求
@CrossOrigin
//以json形式返回
@ResponseBody
//控制器
@Controller
@SuppressWarnings("deprecation")
public class RoleController {
	// 日志打印
	private final Logger logger =  LoggerFactory.getLogger(RoleController.class);
	// 依赖注入
	@Autowired
	RoleService roleService;
	/**
	 * 添加角色
	 * @param role
	 */
	@RequestMapping(value = "addRole", method = RequestMethod.POST)
	public Result<Role> addRole(Role role) {
		Result<Role> result = new Result<>();
		try {
			// 日志打印
			logger.info("\n 添加角色(addRole)开始 Role = " + role.toString());
			if(roleService.addRole(role)) {
				result.setSuccess("添加角色成功！");
			}else {
				result.setError("添加失败！已经存在此用户");
			}
			logger.info("\n 添加角色(addRole)结束 result = " + result.toString());
			return result;
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("添加失败！");
			return result;
		}
	}
	
	/**
	 * 查询所有角色
	 */
	@RequestMapping(value = "findRoleAll", method = RequestMethod.GET)
	public Result<Role> findRoleAll(
			@RequestParam(name = "isAva", defaultValue="true") Boolean isAva,
			@RequestParam(name = "page",defaultValue="0") Integer page,
			@RequestParam(name = "size", defaultValue="10") Integer size) {
		Result<Role> result = new Result<>();	// 存放返回信息
		logger.info("\n 查询所有角色（findRoleAll）开始 ：isAva="+isAva);
		
		try {
			// 分页信息
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			
			Pages pages = null;  // 分页信息
			
			Page<Role> roles = null; // 存放查询信息
			// 查询
			roles = roleService.findRoleAll(isAva, pageRequest);
			
			if(roles != null && roles.getContent() != null && roles.getContent().size() > 0) {
				pages = new Pages(page, roles.getTotalElements(), size);
				
				result.setData(roles.getContent());
				result.setPages(pages);
				
				result.setSuccess("查询成功！");
			}else {
				result.setError("暂无角色信息，请稍后再试！");
			}
			
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("查询失败!发生异常");
		}
		logger.info("\n 查询所有角色（findRoleAll）结束：result="+result.toString());
		return result;
	}
	
	/**
	 * 根据Id查询角色
	 */
	@RequestMapping(value = "findRoleById", method = RequestMethod.GET)
	public Result<Role> findRoleById(Long id) {
		Result<Role> result = new Result<>();
		logger.info("\n 根据Id查询角色（findRoleById）开始 ：id="+id);
		try {
			List<Role> roles = new ArrayList<>();
			
			Role role = roleService.findRoleById(id);
			
			if(role != null) {
				roles.add(role);
				result.setData(roles);
				
				result.setSuccess("查询成功！");
			}else {
				result.setError("查询失败！无此角色信息");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("查询失败！发生异常");
		}
		logger.info("\n 根据Id查询角色（findRoleById）结束 ：result="+result);
		return result;
	}
	/**
	 * 修改角色是否可用
	 * @param id
	 */
	@RequestMapping(value = "setRoleAvailable", method = RequestMethod.PUT)
	public Result<Role> setRoleAvailable(Long id) {
		logger.info("\n 根据Id修改角色是否可用（setRoleAvailable）开始 ：id="+id);
		Result<Role> result = new Result<>();
		
		try {
			if(roleService.setRoleAvailable(id)) {
				result.setSuccess("更新成功！");
			}else {
				result.setError("更新失败！无此角色");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("更新失败！发生异常");
		}
		
		logger.info("\n 根据Id修改角色是否可用（setRoleAvailable）结束 ：result="+result);
		return result;
	}
	
	/**
	 * 根据Key关键字查询角色
	 * @param isAva		是否可用
	 * @param key		关键字
	 * @param page		第几页
	 * @param size		没有显示数据
	 * @return
	 */
	@RequestMapping(value = "findRoleByKey", method = RequestMethod.GET)
	public Result<Role> findRoleByKey(
			@RequestParam(name = "isAva", defaultValue="true") Boolean isAva,
			@RequestParam(name = "key", defaultValue="") String key,
			@RequestParam(name = "page",defaultValue="0") Integer page,
			@RequestParam(name = "size", defaultValue="10") Integer size) {
		logger.info("\n 根据Key关键字查询角色(findRoleByKey)开始 key = " + key+"\t isAva="+isAva);// 日志打印
		Result<Role> result = new Result<>();  // 存放返回数据
		
		try {
			// 分页信息
			Order order 	= new Order(Direction.ASC, "id"); // 根据字段id进行升序排序
			
			PageRequest pageRequest = PageRequest.of(page, size, new Sort(order));// 分页排序查询
			
			Pages pages = null;   // 分页信息
			Page<Role> roles = null;  // 存放查询后的数据
			
			if (Tool.isNumber(key)) {
				return findRoleById(new Long(key));
			}else {
				roles = roleService.findRoleByKey(key, isAva, pageRequest);
			}
			// 判断是否查询到了数据
			if(roles != null && roles.getContent() != null && roles.getContent().size() > 0) {
				pages = new Pages(page, roles.getTotalElements(), size);
				
				result.setPages(pages);
				result.setData(roles.getContent());
				
				result.setSuccess("查询成功！");
			}else {
				result.setError("无此用户存在！");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.setError("查询发生异常！");
		}
		logger.info("\n 根据Key关键字查询部门(findDepaByKey)结束 result = " + result);
		return result;
	}
}
